<?php
declare(strict_types=1);
namespace Service\CommodityService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\PssLogModel\MessageSkuChangeLog;
use App\Amqp\Producer\PushChannelCommodityMessageProducer;
use Hyperf\Amqp\Producer;
use Service\HttpRequest\Http;
use Service\ConsumerService\PushUserGoodsMessageService;

/**
 * 消息模板推送管理中心进行批量推送入库
 */
class GoodsNotifyMessageStorage extends BaseService
{
    /**
     * 推送消息变更goodsChange
     * @param array $binfo
     * @param array $body
     * @param int $source 1-代表主档案引起变更 ， 2-代表供应商商品引起变更
     */
    public function goodsChange(array $binfo,array $body = [], int $source = 0 )
    {
        //如果是自营BBC渠道
        if( $binfo['is_channel'] == 1 ) {
            $goodsCopIds = array_column($body,'goodsCopID');
            $body = array_map(function( & $value)
            {
                return (string)$value;
            },$goodsCopIds);
            $message = [
                'bid'           => $binfo['bid'],
                'cid'           => $binfo['channel_id'],
                'message'       => $body,
                'messageType'   => GoodsNotifyType::GOODS_SKU_BATCH_CHANGE,
                'messageDesc'   => '商品SKU批量更新',
            ];
            return $this->publishChannelHttpMsg($message);
        }
        $message = [
            "MessageType" => GoodsNotifyType::GOODS_CHANGE,
            "Source"      => $source,
            "data"        => $body
        ];
        return $this->addMessageLog($binfo,$message);
    }
    
    /**
     * 推送消息goodsSkuChange
     * @param array $binfo
     * @param array $body
     * @param int $source 1-代表主档案引起变更 ， 2-代表供应商商品引起变更
     */
    public function goodsSkuChange(array $binfo,array $body = [],int $source = 0 )
    {
        if( empty($body) ) {
            return Normal::returnCode(Normal::FAIL,"需要下架的skuList不能为空");
        }
        
        $body = array_filter($body);
        if( empty($body) ) {
            return Normal::returnCode(Normal::FAIL,"需要下架的skuList不能为空");
        }
        
        $body = array_map(function( & $value) 
        {
            return (string)$value;
        },$body);
                
        //如果是自营BBC渠道
        if( $binfo['is_channel'] == 1 ) {
            $message = [
                'bid'           => $binfo['bid'],
                'cid'           => $binfo['channel_id'],
                'message'       => $body,
                'messageType'   => GoodsNotifyType::GOODS_SKU_BATCH_DOWN,
                'messageDesc'   => '商品SKU批量下架',
            ];
            return $this->publishChannelHttpMsg($message);
        }
        
        $message = [
            "MessageType" => GoodsNotifyType::GOODS_SKU_CHANGE,
            "Source"      => $source,
            "data"        => [
                'skuList'   => $body
            ]
        ];
        return $this->addMessageLog($binfo,$message);
    }
    
    /**
     * 推送消息goodsClassChange
     * @param array $binfo
     * @param array $body
     */
    public function classChange(array $binfo,array $body = [] )
    {
        $message = [
            "MessageType" => GoodsNotifyType::CLASS_CHANGE,
            "data"        => $body
        ];
        return $this->addMessageLog($binfo,$message);
    }
    
    /**
     * 推送消息brandChange
     * @param array $binfo
     * @param array $body
     */
    public function brandChange(array $binfo,array $body = [] )
    {
        $message = [
            "MessageType" => GoodsNotifyType::BRAND_CHANGE,
            "data"        => $body
        ];
        return $this->addMessageLog($binfo,$message);
    }
    
    /**
     * 推送消息countryChange
     * @param array $binfo
     * @param array $body
     */
    public function countryChange(array $binfo,array $body = [] )
    {
        $message = [
            "MessageType" => GoodsNotifyType::COUNTRY_CHANGE,
            "data"        => $body
        ];
        return $this->addMessageLog($binfo,$message);
    }
    
    /**
     * 推送消息unitChange
     * @param array $binfo
     * @param array $body
     */
    public function unitChange(array $binfo,array $body = [] )
    {
        $message = [
            "MessageType" => GoodsNotifyType::UNIT_CHANGE,
            "data"        => $body
        ];
        return $this->addMessageLog($binfo,$message);
    }
    
    /**
     * 推送消息tagChange
     * @param array $binfo
     * @param array $body
     */
    public function tagChange(array $binfo,array $body = [] )
    {
        $message = [
            "MessageType" => GoodsNotifyType::TAG_CHANGE,
            "data"        => $body
        ];
        return $this->addMessageLog($binfo,$message);
    }
    
    /**
     * 推送消息spuChange
     * @param array $binfo
     * @param array $body
     */
    public function spuChange(array $binfo,array $body = [] )
    {
        $message = [
            "MessageType" => GoodsNotifyType::SPU_CHANGE,
            "data"        => $body
        ];
        return $this->addMessageLog($binfo,$message);
    }
    
    /**
     * 入库消息数据
     * @param array $messsage
     */
    public function addMessageLog( array $binfo, array $messsage = [] )
    {
        if( $binfo['is_router_user'] == 1 ) {
            return Normal::returnCode(Normal::SUC,"路由用户不需要推送商品数据");
        }
        
        if( $binfo['open_url'] == '1' ) {
            return Normal::returnCode(Normal::SUC,"当前渠道不需要推送数据");
        }
        
        if( empty($binfo['open_url']) && $binfo['bid'] > 0 && empty($binfo['user_tag']) ) {
            return Normal::returnCode(Normal::FAIL,"【{$binfo['name']}】需要推送open_url不能为空，请检查当前渠道推送地址");
        }
        
        if( empty($messsage['data']) ) {
            return Normal::returnCode(Normal::FAIL,"需要推送的数据不能为空");
        }
        
        try {
            $data = [
                'bid'           => $binfo['bid'],
                'message_type'  => $messsage['MessageType'],
                'push_url'      => $binfo['open_url'],
                'contents'      => json_encode($messsage,JSON_UNESCAPED_UNICODE),
                'cd'            => time()
            ];
            $res = MessageSkuChangeLog::instance()->add($data);
            if( $res ) {
                return Normal::returnCode(Normal::SUC,"操作成功");
            }
            return Normal::returnCode(Normal::FAIL,"操作失败");
        } catch ( \Exception $e ) {
            return Normal::returnCode(Normal::FAIL,"写入消息日志失败【{$e->getMessage()}】");
        }
    }
    
    /**
     * 发布新版本BBC商品消息推送功能
     * @param array $msg
     */
    public function publishChannelMsg( array $msg  = [] )
    {
        try {
            $handlerMessage = new PushChannelCommodityMessageProducer($msg);
            $producer = container()->get(Producer::class);
            $result = $producer->produce($handlerMessage,true);
            if( $result ) {
                return Normal::returnCode(Normal::SUC,"发布成功");
            }
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍微再试[100000]");
        } catch ( \Throwable $e ) {
            return Normal::returnCode(Normal::FAIL,"操作失败，请稍微再试[{$e->getMessage()},{$e->getLine()},{$e->getFile()}]");
        }
    }
    
    /**
     * 发布http消息
     * @param array $message
     */
    public function publishChannelHttpMsg(array $message) 
    {
        //推送标准下游三方接口
        $postHead   = [
            "User-Agent: server",
            "Content-Type: application/json",
        ];
        $push_url = PushUserGoodsMessageService::instance()->getSelfYunCangBbcChannelURL();
        $res = Http::apiRequest($push_url, $message, 'post',$postHead, 30, false,'json');
        $httpcode = Http::getHttpCode();
        $push_result = @json_decode((string)$res,true);
        if( isset($push_result['code']) ) {
            return $push_result;
        }
        return Normal::returnCode(Normal::FAIL,"返回JSON格式不正确【{$res}】");
    }
}